package com.zeyu.framework.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.zeyu.framework.core.web.BaseController;
import com.zeyu.framework.core.web.Result;
import com.zeyu.framework.modules.sys.entity.Office;
import com.zeyu.framework.modules.sys.service.OfficeService;
import com.zeyu.framework.modules.sys.utils.UserUtils;
import com.zeyu.framework.utils.StringUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 机构Controller
 */
@Controller
@RequestMapping(value = "/sys/office")
public class OfficeController extends BaseController {

    // ================================================================
    // Constants
    // ================================================================

    // ================================================================
    // Fields
    // ================================================================

    @Autowired
    private OfficeService officeService;

    // ================================================================
    // Constructors
    // ================================================================

    // ================================================================
    // Methods from/for super Interfaces or SuperClass
    // ================================================================

    // ================================================================
    // Public or Protected Methods
    // ================================================================

    @ModelAttribute("office")
    public Office get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return officeService.get(id);
        } else {
            return new Office();
        }
    }

    /**
     * 部门列表页
     */
    @RequiresPermissions("sys:office:view")
    @RequestMapping(value = {"", "index"})
    public String index() {
        return "modules/sys/officeList";
    }

    /**
     * 获取部门列表
     */
    @RequiresPermissions("sys:office:view")
    @RequestMapping(value = "list")
    @ResponseBody
    public List<Office> list(Office office) {
        List<Office> sourceList;
        if (office != null && office.getParentIds() != null) {
            sourceList = officeService.findList(office);
        } else {
            sourceList = officeService.findAll();
        }
        // 因为是tree table,必须指定顺序
        List<Office> offices = Lists.newArrayList();
        // 排序
        Office.sortList(offices, sourceList, Office.getRootId(), true);

        return offices;
    }

    /**
     * 保存部门
     */
    @RequiresPermissions("sys:office:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(@Validated Office office) {
        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }

        officeService.save(office);

        String id = "0".equals(office.getParentId()) ? "" : office.getParentId();
        String params = "id=" + id + "&parentIds=" + office.getParentIds();

        result.setStatus(Result.SUCCESS);
        result.setMessage("保存机构'" + office.getName() + "'成功");
        result.setData(params);

        return result;
    }

    /**
     * 删除菜单
     */
    @RequiresPermissions("sys:office:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public Result delete(Office office) {
        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }
        // 根节点不允许删除
        if (Office.isRoot(office.getId())) {
            result.setStatus(Result.ERROR);
            result.setMessage("删除机构失败, 不允许删除顶级机构或编号空");
        } else {
            officeService.delete(office);
            result.setStatus(Result.SUCCESS);
            result.setMessage("删除机构成功");
            String params = "id=" + office.getParentId() + "&parentIds=" + office.getParentIds();
            result.setData(params);
        }
        return result;
    }

    /**
     * 获取机构JSON数据。
     *
     * @param extId 排除的ID
     * @param type  类型（1：公司；2：部门：3：小组; 4:其它）
     * @param grade 显示级别
     * @return office tree
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
                                              @RequestParam(required = false) String type,
                                              @RequestParam(required = false) Long grade) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = officeService.findAll();
        list.stream().filter(e -> (StringUtils.isBlank(extId) || (!extId.equals(e.getId())
                && !e.getParentIds().contains("," + extId + ",")))
                && (type == null || ((!type.equals("1") || type.equals(e.getType()))))
                && (grade == null || (Integer.parseInt(e.getGrade()) <= grade.intValue()))
                && YES.equals(e.getUseable()))
                .forEach(e -> {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", e.getId());
                    map.put("pId", e.getParentId());
                    map.put("pIds", e.getParentIds());
                    String oname = "<i class='" + UserUtils.getIconByType(e) + "'></i> " + StringUtils.replace(e.getName(), " ", "");
                    map.put("name", oname);

                    mapList.add(map);
                });
        return mapList;
    }

    // ================================================================
    // Getter & Setter
    // ================================================================

    // ================================================================
    // Private Methods
    // ================================================================

    // ================================================================
    // Inner or Anonymous Class
    // ================================================================

    // ================================================================
    // Test Methods
    // ================================================================
}
